/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.smart.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zhanghong
 * @version Base64MultipartFile.java, v 0.1 2023/8/8 11:33 下午 Base64MultipartFile Exp $$
 */
class Base64MultipartFile implements MultipartFile {

    private final byte[] content;
    private final String contentType;
    private final String name;

    public Base64MultipartFile(byte[] content, String contentType) {
        this.content = content;
        this.contentType = contentType;
        this.name = "image";
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return name + "." + getExtension();
    }

    private String getExtension() {
        String[] parts = contentType.split("/");
        return parts[1];
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return content == null || content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() {
        return content;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        new FileOutputStream(file).write(content);
    }
}
